package file;

import java.io.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 张杰
 * Date: 2022-04-19
 * Time: 20:46
 */
//案例3:扫描指定目录,并找到名称或者内容包括包含指定字符的所有普通字符
public class Demo10 {
    public static void main(String[] args) throws IOException {
        //1.输入要扫描的文件路径
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要扫描的路径: ");
        String rootDirPath = scanner.next();
        System.out.println("请输入要查询的关键词: ");
        String word = scanner.next();
        File rootDir = new File(rootDirPath);
        if(!rootDir.isDirectory()) {
            System.out.println("输入的路径非法!");
            return;
        }
        //2.递归的进行遍历
        scsnDir(rootDir,word);
    }

    private static void scsnDir(File rootDir, String word) throws IOException {
        //1.先列出rootDir都有哪些内容
        File[] files = rootDir.listFiles();
        if(files == null) {
            return;
        }
        //2.遍历每个元素,针对普通元素和目录分别进行处理.
        for (File f: files) {
            //普通文件
            if(f.isFile()) {
                //针对文件进行内容查找
                if(coutainsWord(f,word)) {
                    System.out.println(f.getCanonicalPath());
                }
            } else if(f.isDirectory()) {
                //针对目录进行递归
                scsnDir(f,word);
            }
        }
    }

    private static boolean coutainsWord(File f, String word) {
        StringBuilder stringBuilder = new StringBuilder();
        try(Reader reader = new FileReader(f)) {
            //将文件的内容读到stringBuilder
            char[] buffer = new char[1024];
            while(true) {
                int len = reader.read(buffer);
                if(len == -1) {
                    break;
                }
                //将读到的内容拼接到StringBuilder中
                stringBuilder.append(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //判断是否包含word
        return stringBuilder.indexOf(word) != -1;
    }

}
